<template>
  <view class="signature-box">
    <!-- 签名 -->
    <view class="signature" v-show="showCanvas">
      <text class="tips">请在以下区域签名：</text>
      <canvas
        class="mycanvas"
        canvas-id="mycanvas"
        @touchstart="touchstart"
        @touchmove="touchmove"
        @touchend="touchend"
      ></canvas>
      <view class="footer">
        <u-button @click="clear" type="warning" shape="square" :ripple="true" size="medium" ripple-bg-color="#909399"
          >重签</u-button
        >
        <u-button @click="finish" type="primary" shape="square" :ripple="true" size="medium" ripple-bg-color="#909399"
          >签署</u-button
        >
        <!-- <u-button @click="close" type="primary" :plain="true" :ripple="true" ripple-bg-color="#909399">关闭</u-button> -->
      </view>
    </view>

    <view class="toast" v-if="isShowTips">请在签字区域进行签名！</view>

    <!-- 签完名后生成的图片 -->
    <view v-show="SignatureImg" class="SignatureImg"><image :src="SignatureImg" mode=""></image></view>

    <!-- 清除签完名后生成的图片 -->
    <!-- <u-button
      v-show="SignatureImg"
      @click="obliterate"
      type="error"
      :plain="true"
      :ripple="true"
      ripple-bg-color="#909399"
      size="medium"
      >清除签名</u-button
    > -->
  </view>
</template>

<script>
var x = 20;
var y = 20;
export default {
  data() {
    return {
      //绘图图像
      ctx: "",
      //路径点集合
      points: [],
      //签名图片
      SignatureImg: "",
      hasDrawIamge: false, //是否有绘画
      isShowTips: false,
    };
  },
  props: ["showCanvas"],
  methods: {
    //清除签名的图片
    obliterate() {
      if (this.SignatureImg) {
        this.SignatureImg = "";
      }
      this.close();
    },
    //关闭并清空画布
    close() {
      this.$emit("closeCanvas");
      this.clear();
    },
    //创建并显示画布
    createCanvas() {
      this.ctx = uni.createCanvasContext("mycanvas", this); //创建绘图对象
      //设置画笔样式
      this.ctx.lineWidth = 4;
      this.ctx.lineCap = "round";
      this.ctx.lineJoin = "round";
    },
    //触摸开始，获取到起点
    touchstart(e) {
      let startX = e.changedTouches[0].x;
      let startY = e.changedTouches[0].y;
      let startPoint = { X: startX, Y: startY };
      this.points.push(startPoint);
      //每次触摸开始，开启新的路径
      this.ctx.beginPath();
    },
    //触摸移动，获取到路径点
    touchmove(e) {
      let moveX = e.changedTouches[0].x;
      let moveY = e.changedTouches[0].y;
      let movePoint = { X: moveX, Y: moveY };
      this.points.push(movePoint); //存点
      let len = this.points.length;
      if (len >= 2) {
        this.draw(); //绘制路径
      }
    },
    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
    touchend() {
      this.points = [];
    },
    //绘制笔迹
    draw() {
      let point1 = this.points[0];
      let point2 = this.points[1];
      this.points.shift();
      this.ctx.moveTo(point1.X, point1.Y);
      this.ctx.lineTo(point2.X, point2.Y);
      this.ctx.stroke();
      this.ctx.draw(true);
      this.hasDrawIamge = true;
    },
    //清空画布
    clear() {
      // 恢复未签名标志位
      this.hasDrawIamge = false;
      let that = this;
      uni.getSystemInfo({
        success: function (res) {
          let canvasw = res.windowWidth;
          let canvash = res.windowHeight;
          that.ctx.clearRect(0, 0, canvasw, canvash);
          that.ctx.draw(true);
        },
      });
    },
    //完成绘画并保存到本地
    finish() {
      let that = this;
      if (!that.hasDrawIamge) {
        this.isShowTips = true;
        setTimeout(() => {
          this.isShowTips = false;
        }, 1000);
        return false;
      }
      uni.canvasToTempFilePath(
        {
          canvasId: "mycanvas",
          success: function (res) {
            that.rotateBase64Img(res.tempFilePath, 270, (url) => {
              that.SignatureImg = url;
              that.$emit("finish", url);
            });
          },
        },
        this
      );
    },
    rotateBase64Img(src, edg, callback) {
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      if (edg % 90 != 0) {
        console.error("旋转角度必须是90的倍数!");
        throw "旋转角度必须是90的倍数!";
      }
      edg < 0 && (edg = (edg % 360) + 360);
      var image = new Image();
      image.crossOrigin = "anonymous";
      image.src = src;
      image.onload = function () {
        // 2.1 设置canvas宽高，旋转90° ，宽高互换
        canvas.width = image.height;
        canvas.height = image.width;
        // 2.2 画布中心点(也是起始点)平移至中心(0,0)->(x,y)
        ctx.translate(canvas.width / 2, canvas.height / 2);
        // 2.3 画布旋转90°
        ctx.rotate(edg * Math.PI / 180);
        // 2.4 绘制图像 图像起始点需偏移负宽高
        ctx.scale(0.7,0.8);
        ctx.drawImage(image, -image.width / 2, -image.height / 2);
        // 2.5返回结果(base64)
        callback(canvas.toDataURL());
      };
    },
  },
  mounted() {
    document.body.addEventListener(
      "touchmove",
      (e) => {
        e.preventDefault();
      },
      { passive: false }
    );
    this.createCanvas();
  },
};
</script>

<style lang="scss" scoped>
.signature-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  //签名模块
  .signature {
    position: fixed;
    top: 10px;
    left: 2%;
    z-index: 999;
    width: 96%;
    //canvas
    .mycanvas {
      width: 100%;
      height: calc(100vh - 200upx);
      background-color: #ececec;
    }
    //底部按钮
    .footer {
      font-size: 14px;
      height: 150upx;
      display: flex;
      justify-content: space-around;
      align-items: center;
    }
  }
  //生成的图片
  .SignatureImg {
    image {
      width: 750rpx;
      height: 750rpx;
    }
  }
  .tips {
    color: #666;
    font-size: 12px;
  }
}
@media screen and (orientation: portrait) {
  .toast {
    position: fixed;
    z-index: 999;
    padding: 10px;
    top: 50%;
    left: 50%;
    background: rgba(17, 17, 17, 0.7);
    text-align: center;
    border-radius: 5px;
    color: #fff;
    transform: rotate(90deg) translate(-50%, -50%) !important;
    transform-origin: 0 100%;
  }
  .mycanvas {
    margin-left: 140upx;
    width: calc(100vw - 220upx) !important;
    height: calc(100vh - 40upx) !important;
  }
  .tips {
    transform: rotate(90deg);
    transform-origin: 0 100%;
    width: calc(95vh);
    display: block;
    position: absolute;
    z-index: 111;
    left: calc(91vw);
    top: -17px;
  }
  .footer {
    transform: rotate(90deg);
    transform-origin: 0 100%;
    width: calc(95vh);
    position: absolute;
    z-index: 111;
    left: calc(-7px);
    height: 60px;
    top: -10vh;
  }
}
</style>
